import { useSize } from 'ahooks'
import React, { HTMLAttributes, useRef } from 'react'

interface SizeWatchProps extends HTMLAttributes<any> {
  children: React.ReactElement
}

/**
 * 容器大小监听组件，会向子组件通过属性传递当前容器的信息，包含
 * - 容器宽度 parentWidth
 * - 容器高度 parentHeight
 * - 容器本身 parentRef
 */
export const SizeWatch = (props: SizeWatchProps) => {
  const containerRef = useRef(null)
  const containerSize = useSize(containerRef)

  const { children: propChildren, className, style } = props

  const newProps = {
    parentWidth: containerSize?.width,
    parentHeight: containerSize?.height,
    parentRef: containerRef,
  }
  const children = React.cloneElement(propChildren, newProps)

  return (
    <div className={className} style={style} ref={containerRef}>
      {children}
    </div>
  )
}
